package file.day9_20.day06.服务端和客户端多线程01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private ServerSocket serverSocket;

    public Server(){
        System.out.println("正在启动一个服务器");

        try {
            serverSocket = new ServerSocket(8091);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("启动服务器完毕");
    }

    public void start(){
        try {
            while (true){
                System.out.println("等待客户端的连接");
                Socket socket = serverSocket.accept();
                System.out.println("客户端连接成功");

                //多线程处理
                ClientHandler clientHandler = new ClientHandler(socket);
                Thread t = new Thread(clientHandler);
                t.start();
            }



        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable{
        private Socket socket;

        public ClientHandler(Socket socket){
            this.socket = socket;
        }

        public void run(){


            try{
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream(),"UTF-8"
                        )
                );

                String line;
                while ((line = br.readLine()) != null){
                    System.out.println(line);
                    System.out.println("接收成功");
                }
            }catch (IOException e){
                e.printStackTrace();
            }

        }
    }
}
